import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/account_api.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/request/real_auth_request.dart';
import 'package:sainbainu/common/repositories/account_repository.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/utils/custom_exception.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/widgets/widget.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'index.dart';

class RealNameAuthController extends GetxController {
  RealNameAuthController();

  final state = RealNameAuthState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.nameController = TextEditingController();
    state.idCardController = TextEditingController();
    state.accountRepository = AccountRepository(AccountApi());
    if (UserService.to.accountInfo.value.realFlag == 1) {
      state.nameController.text =
          UserService.to.accountInfo.value.realName ?? '';
      state.idCardController.text =
          UserService.to.accountInfo.value.idCard ?? '';
      state.isRealed = true;
    }
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.nameController.dispose();
    state.idCardController.dispose();
  }

  /// 确认提交
  void handleSubmit() async {
    try {
      if (state.nameController.text.isEmpty) {
        throw CustomException('请输入真实姓名'.tr);
      }
      if (state.idCardController.text.isEmpty) {
        throw CustomException('请输入身份证号'.tr);
      }
      LoadingUtil.showLoading(text: '提交中...');
      await state.accountRepository.realAuth(RealAuthRequest(
        realName: state.nameController.text,
        idCard: state.idCardController.text,
      ));
      await UserService.to.getAccountInfo();
      LoadingUtil.showSuccess('实名认证成功');
      Get.back();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.message);
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }
}
